<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Service\FlyAddressService;
use Psr\Http\Message\ResponseInterface;
use Hyperf\Di\Annotation\Inject;

/**
 * 用户收货地址
 * Class AddressController
 * @package App\Controller
 */
class AddressController extends AbstractController
{
    /**
     * @Inject
     * @var FlyAddressService
     */
    private $flyAddr;

    /**
     * 获取用户ID
     * @return int
     */
    public function get_user_id(): int
    {
        return (int)$this->request->getHeaderLine('admin_id') ?? 0;
    }

    /**
     * 获取我的收货地址列表
     * @return ResponseInterface
     */
    public function getMyAddress(): ResponseInterface
    {
        $user_id = $this->get_user_id();
        if (!$user_id) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '未登录请先登录');
        }
        return $this->jsonResponse->success($this->flyAddr->getMyAddress($user_id));
    }

    /**
     * 设置收获地址（新增|修改|设置默认）
     * @return ResponseInterface
     */
    public function setMyAddress(): ResponseInterface
    {
        $user_id = $this->get_user_id();
        if (!$user_id) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '未登录请先登录');
        }
        $params = $this->request->all();
        $params['user_id'] = $user_id;
        $v_data = $this->flyAddr->verifyGetData($params);
        if (!$v_data['res']) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, $v_data['msg']);
        }
        $id = $this->flyAddr->setAddress($v_data['data']);
        if (!$id) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '操作失败');
        }
        return $this->jsonResponse->success(['address_id' => $id], '操作成功');
    }

    /**
     * 删除收货地址
     * @return ResponseInterface
     */
    public function delAddress(): ResponseInterface
    {
        $user_id = $this->get_user_id();
        if (!$user_id) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '未登录请先登录');
        }
        $addr_id = $this->request->input('id', 0);
        $res = $this->flyAddr->delAddress(['user_id' => $user_id, 'id' => $addr_id]);
        if (!$res) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '删除失败');
        }
        return $this->jsonResponse->success([], '删除成功');
    }
}